package com.zerosky.crm.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zerosky.crm.po.Department;
import com.zerosky.crm.po.Employee;
import com.zerosky.crm.po.Notice;
import com.zerosky.crm.service.DepartmentService;
import com.zerosky.crm.service.NoticeService;
import com.zerosky.crm.util.BaseAction;
import com.zerosky.crm.util.PageInfo;

/**
 * 通知相关业务的Controller
 * 
 * @author 钟璟
 *
 */
@Controller
public class NoticeController extends BaseAction {

	private Logger logger = LoggerFactory.getLogger(NoticeController.class); // 日志

	@Resource(name = "noticeService")
	private NoticeService noticeService;

	@Resource(name = "departmentService")
	private DepartmentService departmentService;

	/**
	 * 跳转我的工作台通知界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toNotice.do")
	public ModelAndView toNotice(HttpServletRequest request, HttpSession session, HttpServletResponse response,
			String id) throws Exception {
		if ("1?v=4.0".equals(id)) {
			// 跳转到公告页面
			return new ModelAndView("WEB-INF/jsp/staging/announcementList");
		} else {
			// 跳转到通知页面
			return new ModelAndView("WEB-INF/jsp/staging/noticeList");
		}
	}

	/**
	 * 跳转系统管理通知界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toSystemNoticeList.do")
	public ModelAndView toSystemNoticeList(HttpServletRequest request, HttpSession session,
			HttpServletResponse response, String id) throws Exception {
		List<Department> list = departmentService.getDepartmentList(null);
		request.setAttribute("dept", list);
		if ("1?v=4.0".equals(id)) {
			return new ModelAndView("WEB-INF/jsp/system/announcementList");
		} else {
			return new ModelAndView("WEB-INF/jsp/system/noticeList");
		}
	}

	/**
	 * 跳转系统添加公告界面
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/toAddAnnouncement.do")
	public ModelAndView toAddAnnouncement(HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		return new ModelAndView("WEB-INF/jsp/system/addAnnouncement");
	}

	/**
	 * 富文本图片上传
	 * 
	 * @param request
	 * @param response
	 * @param upload
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/ckeditorUpload.do",produces="text/html;charset=UTF-8")
	public String ImageUpload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("upload") MultipartFile upload) {
		response.setContentType("text/html; charset=UTF-8");
		response.setContentType("application/json;charset=UTF-8");// 防止数据传递乱码
		response.setCharacterEncoding("UTF-8");
		String callback = request.getParameter("CKEditorFuncNum");
		String path = request.getSession().getServletContext().getRealPath("/") + "saituImage/";
		String imgName = "";
		String json = ""; // 返回的json数据
		/* 上传到服务器 */
		try {

			File targetFile = new File(path);

			// 如过该文件夹不存在，则创建
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}

			if (!upload.isEmpty()) {
				// 获得文件类型（可以判断如果不是图片，禁止上传）
				String uploadContentType = upload.getContentType();

				String expandedName = ""; // 文件扩展名
				if (uploadContentType.equals("image/pjpeg") || uploadContentType.equals("image/jpeg")) {
					// IE6上传jpg图片的headimageContentType是image/pjpeg，而IE9以及火狐上传的jpg图片是image/jpeg
					expandedName = ".jpg";
				} else if (uploadContentType.equals("image/png") || uploadContentType.equals("image/x-png")) {
					// IE6上传的png图片的headimageContentType是"image/x-png"
					expandedName = ".png";
				} else if (uploadContentType.equals("image/gif")) {
					expandedName = ".gif";
				} else if (uploadContentType.equals("image/bmp")) {
					expandedName = ".bmp";
				} else {
					json = "<script type=\"text/javascript\">" + "window.parent.CKEDITOR.tools.callFunction(" + callback
							+ ",''," + "'文件格式不正确（必须为.jpg/.gif/.bmp/.png文件）');" + "</script>";
					return json;
				}

				/*
				 * if(upload.length() > 600*1024){ out.println(
				 * "<script type=\"text/javascript\">");
				 * out.println("window.parent.CKEDITOR.tools.callFunction(" +
				 * callback + ",''," + "'文件大小不得大于600k');");
				 * out.println("</script>"); return null; }
				 */

				// 获取UUID和图片后缀=图片名
				String uuid = UUID.randomUUID().toString().replace("-", "");
				imgName = uuid + expandedName;
				upload.transferTo(new File(path + imgName));

				/* 返回富文本 */
				/*
				 * "http://" + request.getServerName() // 服务器地址 + ":" +
				 * request.getServerPort() // 端口号 + request.getContextPath() +
				 * "/
				 */
				// String url = "http://crm.binhaigc.com/saituImage/" + imgName;
				String url = "http://" + request.getServerName() + ":" + request.getServerPort()
						+ request.getContextPath() + "/saituImage/" + imgName;
				json = "<script type=\"text/javascript\">" + "window.parent.CKEDITOR.tools.callFunction(" + callback
						+ ",'" + url + "',''" + ")" + "</script>";
			} else {
				json = "<script type=\"text/javascript\">" + "window.parent.CKEDITOR.tools.callFunction(" + callback
						+ ",''," + "'错误上传');" + "</script>";
			}
		} catch (Exception e) {
			logger.error("获取数据失败，原因：" + e);
			json = "<script type=\"text/javascript\">" + "window.parent.CKEDITOR.tools.callFunction(" + callback
					+ ",''," + "'未知错误');" + "</script>";
		}
		return json;
	}

	/**
	 * 获取通知列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/noticeList.do")
	@ResponseBody
	public Map<String, Object> noticeList(Integer limit, Integer page, String title, String sysNotice,
			HttpServletRequest request, HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Map<String, Object> param = new HashMap<String, Object>();// 定义条件集合
		Employee user = (Employee) session.getAttribute("loginUser");// 获取当前用户信息
		PageInfo<Notice> pageInfo = new PageInfo<Notice>();
		try {
			// map.put("empId", user.getEmployeeId());//属于当前登录用户的合同
			pageInfo.setPageNo(page);
			pageInfo.setPageSize(limit);
			if (Strings.isNotEmpty(title)) {// 条件查询
				param.put("noticeTitle", title);
			}
			// 标记是否为系统通知公告（如果是系统公告通知就不用控制权限，将所有公告通知都查询出来，否则就有权限控制）
			param.put("sysNotice", sysNotice);
			// 将用户分公司、部门、团队等id传到sql判断控制查询信息
			param.put("deptId", user.getDept() != null ? user.getDept().getDeptId() : null);
			param.put("branchId", user.getBranch() != null ? user.getBranch().getBranchId() : null);
			param.put("teamId", user.getTeam() != null ? user.getTeam().getBranchId() : null);

			param.put("method", "1");
			param.put("status", request.getParameter("status"));
			param.put("noticeStatus", request.getParameter("noticeStatus"));
			json.put("flag", "0");
			PageInfo<Notice> pageRole = noticeService.getPageInfoNoticeList(param, pageInfo);
			json.put("total", pageRole.getPageCount());
			json.put("data", pageRole.getList());
			json.put("flag", "1");
			;

		} catch (Exception e) {
			json.put("flag", "-1");
			logger.error("获取数据失败，原因：" + e);
		}
		return json;

	}

	/**
	 * 删除通知信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/delNotice.do")
	public void delNotice(String id, HttpServletRequest request, HttpSession session, HttpServletResponse response)
			throws Exception {
		try {
			noticeService.deleteNotice(id);
			feedback(response, "1");
		} catch (Exception e) {
			feedback(response, "-1");
			logger.error("获取数据失败，原因：" + e);
		}
	}

	/**
	 * 启用禁用设置
	 * 
	 * @param id
	 *            通知/公告编号
	 * @param noticeStatus
	 *            状态（1、启用；2、禁用）
	 * @param request
	 * @param session
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/updateNoticeStatus.do")
	@ResponseBody
	public Map<String, Object> updateNoticeStatus(String id, int noticeStatus, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("noticeId", id);
		paramMap.put("noticeStatus", noticeStatus);
		return noticeService.updateNoticeStatus(paramMap);
	}

	/**
	 * 请求编辑通知信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/editNotice.do")
	@ResponseBody
	public Map<String, Object> editNotice(String id, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			Notice notice = noticeService.getNoticeById(id);
			if (notice != null) {
				noticeService.updateNoticeRelation(id);
			}
			json.put("notice", notice);
			json.put("code", 1);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 请求编辑通知信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getNewNotice.do")
	@ResponseBody
	public Map<String, Object> getNewNotice(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) {
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户信息
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			Integer count = noticeService.getNewNotice(user.getEmployeeId());
			if (count > 0) {
				json.put("code", 1);
			} else {
				json.put("code", 0);
			}
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 添加通知信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertNotice.do")
	@ResponseBody
	public Map<String, Object> insertNotice(Notice notice, String date1, String oper, HttpServletRequest request,
			HttpSession session, HttpServletResponse response) throws Exception {
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		try {
			String noticeId = UUID.randomUUID().toString();
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			// 时间转为date类型
			Date date = sf.parse(date1);
			notice.setReleaseDate(date);
			if (oper.equals("新增")) {
				// notice.setNoticeState("0");
				notice.setNoticeId(noticeId);
				notice.setCreatePeople(user.getDept() == null ? "管理员" : user.getDept().getDeptName());
				notice.setCreateDate(new Date());
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("noticeId", noticeId);
			map.put("userId", user.getEmployeeId());
			map.put("isRead", 0);
			noticeService.saveOrUpdate(notice, oper);
			noticeService.saveNoticeRelation(map);
			json.put("code", 1);
		} catch (Exception e) {
			json.put("code", -1);
			logger.error("获取数据失败，原因：" + e);
		}
		return json;
	}

	/**
	 * 获取首页通知列表
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/indexNoticeList.do")
	@ResponseBody
	public Map<String, Object> indexNoticeList(HttpServletRequest request, HttpSession session,
			HttpServletResponse response) throws Exception {
		Map<String, Object> json = new HashMap<String, Object>(); // 定义返回map集合
		Map<String, Object> param = new HashMap<String, Object>();// 定义条件集合
		Employee user = (Employee) session.getAttribute("loginUser");// 获取登录用户
		PageInfo<Notice> pageInfo = new PageInfo<Notice>();
		// 将用户分公司、部门、团队等id传到sql判断控制查询信息
		param.put("deptId", user.getDept() != null ? user.getDept().getDeptId() : null);
		param.put("branchId", user.getBranch() != null ? user.getBranch().getBranchId() : null);
		param.put("teamId", user.getTeam() != null ? user.getTeam().getBranchId() : null);
		param.put("noticeStatus", 0);
		try {
			PageInfo<Notice> pageRole = noticeService.getPageInfoNoticeList(param, pageInfo);
			json.put("data", pageRole.getList());
			json.put("flag", "1");

		} catch (Exception e) {
			json.put("flag", "-1");
			logger.error("获取数据失败，原因：" + e);
		}
		return json;

	}
}
